<!--
 * @Description: 交易记录
 *
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-07-03 17:11:54
 * @FilePath: /yuxiuproweb/src/views/money/log/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单ID" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核时间" prop="processTime">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="queryParams.processTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="账户类型" prop="accounttype">
        <el-select
          v-model="queryParams.accounttype"
          placeholder="请选择账户类型"
          style="width: 100%"
        >
          <el-option key="1" label="返利账户" value="1"></el-option>
          <el-option key="2" label="现金账户" value="2"> </el-option>
          <el-option key="3" label="窗帘账户" value="3"> </el-option>
          <el-option key="4" label="墙布账户" value="4"> </el-option>
          <el-option key="5" label="功能帘账户" value="5"> </el-option>
          <el-option key="6" label="喔喔熊账户" value="6"> </el-option>
          <el-option key="7" label="物料账户" value="7"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="moneytype">
        <el-select
          v-model="queryParams.moneytype"
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option key="1" label="收入" value="1" />
          <el-option key="2" label="支出" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="ordertype">
        <el-select
          v-model="queryParams.ordertype"
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option key="1" label="窗帘" value="1" />
          <el-option key="2" label="墙布" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="isprocess">
        <el-select
          v-model="queryParams.isprocess"
          placeholder="请选择审核状态"
          style="width: 100%"
        >
          <el-option key="1" label="已审核" value="1" />
          <el-option key="0" label="未审核" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:record:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
          >导入</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleUpdatesumbit"
          v-hasPermi="['pro:record:remove']"
          >全部审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pro:record:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      :max-height="maxHeight"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column
        label="现金账户扣减"
        align="center"
        prop="transactionRecordId"
      /> -->
      <el-table-column
        label="交易ID"
        align="center"
        prop="transactionRecordId"
      />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="订单类型" align="center" prop="ordertype">
        <template slot-scope="scope">
          <span v-if="scope.row.ordertype == 1">窗帘</span>
          <span v-if="scope.row.ordertype == 2">墙布</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户简称" align="center" prop="clientName" />
      <el-table-column label="账户类型" align="center" prop="accounttype">
        <template slot-scope="scope">
          <span v-if="scope.row.accounttype == 1">返利账户</span>
          <span v-if="scope.row.accounttype == 2">现金账户</span>
          <span v-if="scope.row.accounttype == 3">窗帘账户</span>
          <span v-if="scope.row.accounttype == 4">墙布账户</span>
          <span v-if="scope.row.accounttype == 5">功能帘账户</span>
          <span v-if="scope.row.accounttype == 6">喔喔熊账户</span>
          <span v-if="scope.row.accounttype == 7">物料账户</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="moneytype">
        <template slot-scope="scope">
          <span v-if="scope.row.moneytype == 1">收入</span>
          <span v-if="scope.row.moneytype == 2">支出</span>
        </template>
      </el-table-column>
      <el-table-column label="交易金额" align="center" prop="amount">
        <template slot-scope="scope">
          <span v-if="scope.row.moneytype == 1">{{ scope.row.amount }}</span>
          <span v-if="scope.row.moneytype == 2">-{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账户余额" align="center" prop="cashAccount" />
      <el-table-column
        label="交易时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="审核时间"
        align="center"
        prop="processTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.processTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="120"
        label="审核人"
        align="center"
        prop="process"
      />
      <el-table-column label="审核状态" align="center" prop="isprocess">
        <template slot-scope="scope">
          <span v-if="scope.row.isprocess == 0">未审核</span>
          <span v-if="scope.row.isprocess == 1">已审核</span>
          <span v-if="scope.row.isprocess == 2">审核不通过</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" />
      <el-table-column
        label="操作"
        align="center"
        width="150px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isprocess != 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleProcess(scope.row, 1)"
            >审核通过</el-button
          >
          <el-button
            v-if="scope.row.isprocess != 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pro:record:edit']"
            >修改</el-button
          >
		  <el-button
		    v-if="scope.row.isprocess != 1"
		    size="mini"
		    type="text"
		    icon="el-icon-edit"
		    @click="handleUpdate(scope.row)"
		    v-hasPermi="['pro:record:edit']"
		    >删除</el-button
		  >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :money="money"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      layout="slot,total,sizes,prev, pager, next, jumper"
    >
    </pagination>

    <!-- 添加或修改交易记录对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="客户" prop="clientId">
          <el-select
            style="width: 100%"
            v-model="form.clientId"
            filterable
            placeholder="请选择客户"
            remote
            reserve-keyword
            :remote-method="getListClient"
            @change="handleClientChange"
          >
            <el-option
              v-for="item in clientList"
              :key="item.clientId"
              :label="item.clientNick"
              :value="item.clientId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户编码" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="账目类型" prop="moneytype">
          <el-select
            style="width: 100%"
            v-model="form.moneytype"
            filterable
            placeholder="请输入账目类型"
          >
            <el-option key="1" label="收入" value="1"></el-option>
            <el-option key="2" label="支出" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户类型" prop="accounttype">
          <el-select
            style="width: 100%"
            v-model="form.accounttype"
            filterable
            placeholder="请输入账户类型"
          >
            <el-option key="1" label="返利账户" value="1"></el-option>
            <el-option key="2" label="现金账户" value="2"> </el-option>
            <el-option key="3" label="窗帘账户" value="3"> </el-option>
            <el-option key="4" label="墙布账户" value="4"> </el-option>
            <el-option key="5" label="功能帘账户" value="5"> </el-option>
            <el-option key="6" label="喔喔熊账户" value="6"> </el-option>
            <el-option key="7" label="物料账户" value="7"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="form.amount"
            placeholder="请输入账户金额"
            @blur="form.amount = $event.target.value.trim()"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 收入导入对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link
	        type="primary"
	        :underline="false"
	        style="font-size: 12px; vertical-align: baseline"
	        @click="importTemplate"
	        >下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateProcess,
  sumbitRecord,
  updateRecord,
  handleabandon,
} from "@/api/money/log";
import { getToken } from "@/utils/auth";
import { listClient, getClient } from "@/api/mes/md/client";
import commonMix from "@/utils/mixins/common";

export default {
  mixins: [commonMix],
  name: "Record",
  data() {
    return {
      // 遮罩层
      loading: true,
      clientList: [],
      // 选中数组
      ids: [],
      isprocess: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      money: 0,
      // 交易记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        orderId: null,
        clientCode: null,
        clientName: null,
        cashAccount: null,
        rebateAccount: null,
        otherAccount: null,
      },
      // 收入导入参数
      upload: {
        // 是否显示弹出层（收入导入）
        open: false,
        // 弹出层标题（收入导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的收入数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pro/transactionRecord/importData",
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleClientChange() {
      const { clientCode } = this.clientList?.find(
        (e) => e.clientId === this.form.clientId
      );

      this.form.clientCode = clientCode;
    },
    getListClient(clientName = "") {
      listClient({
        pageNum: 1,
        pageSize: 100,
        enableFlag: "Y",
        clientName,
        // id: "1107",
      }).then(({ rows }) => {
        this.clientList = rows;
      });
    },
    /** 下载模板操作 */
    // importTemplate() {
    //   this.download(
    //     "system/user/importTemplate",
    //     {},
    //     `user_template_${new Date().getTime()}.xlsx`
    //   );
    // },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "收入导入";
      this.upload.open = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    /** 查询交易记录列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        startDate: this.queryParams.processTimeObj?.[0] || null,
        endDate: this.queryParams.processTimeObj?.[1] || null,
      };
      delete params.processTimeObj;
      listRecord(params).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        let filteredStr = response.msg.replace(/[{}]/g, "");
        filteredStr = filteredStr.replace("totalAmountEarn", "收入");
        filteredStr = filteredStr.replace("totalAmountPaid", "支出");
        // let rs = filteredStr.split(",");
        this.money = filteredStr;
        console.log(filteredStr);

        this.loading = false;
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transactionRecordId: null,
        orderId: null,
        clientCode: null,
        clientName: null,
        cashAccount: null,
        rebateAccount: null,
        otherAccount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.transactionRecordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加交易记录";
    },
    handleProcess(row, type) {
      this.reset();
      const transactionRecordId = row.transactionRecordId || this.ids;
      let processdata = {
        transactionRecordId: transactionRecordId,
        isprocess: "1",
      };

      console.log(processdata);
      updateProcess(processdata).then((response) => {
        if (type == 1) {
          this.$modal.msgSuccess("审核成功");
        } else {
          this.$modal.msgSuccess("审核不通过");
        }
        this.open = false;
        this.getList();
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transactionRecordId = row.transactionRecordId || this.ids;
      getRecord(transactionRecordId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改交易记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.transactionRecordId != null) {
            updateRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.orderId == null) {
              this.form.orderId = this.parseTime(new Date(), "{y}{m}{d}");
            }
            console.log(this.form);
            addRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleUpdatesumbit(row) {
      const transactionRecordIds = row.transactionRecordId || this.ids;
      let idv = transactionRecordIds.join(",");
      // let processdata={"ids":idv, "isprocess":1}
      sumbitRecord(idv).then((response) => {
        this.$modal.msgSuccess("审核成功");
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const params = {
        ...this.queryParams,
        startDate: this.queryParams.processTimeObj?.[0] || null,
        endDate: this.queryParams.processTimeObj?.[1] || null,
      };
      delete params.processTimeObj;
      this.download(
        "pro/transactionRecord/export",
        {
          ...params,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal
        .confirm("是否确认删除交易记录？")
        .then(function () {
          return delRecord(recordIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
